package com.feeyar.jswfsocket {
  import com.feeyar.jswfsocket.core.JSocket;

  import flash.display.Sprite;
  import flash.events.Event;
  import flash.events.IOErrorEvent;
  import flash.events.ProgressEvent;
  import flash.events.SecurityErrorEvent;
  import flash.net.Socket;
  import flash.utils.Endian;
  /**
   * @author Wangbin
   */
  public class JSwfSocket extends Sprite {
    //==========================================================================
    //  Constructor
    //==========================================================================
    public function JSwfSocket() {
      initSocket();
      configEventListeners();

      socket.connect("192.168.1.162", 5536);
    }
    //==========================================================================
    //  Variables
    //==========================================================================
    private var socket:Socket;
    //==========================================================================
    //  Public methods
    //==========================================================================
    public function getSocket():JSocket {
      return new JSocket();
    }
    //==========================================================================
    //  Private methods
    //==========================================================================
    private function initSocket():void {
      socket = new Socket();
      socket.endian = Endian.BIG_ENDIAN;
    }
    private function configEventListeners():void {
      socket.addEventListener(Event.CONNECT, socket_connectedHandler);
      socket.addEventListener(Event.CLOSE, socket_closeHandler);
      socket.addEventListener(IOErrorEvent.IO_ERROR, socket_ioErrorHandler);
      socket.addEventListener(ProgressEvent.SOCKET_DATA, socket_socketDataHandler);
      socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, socket_securityErrorHandler);
    }
    //==========================================================================
    //  Event handlers
    //==========================================================================
    private function socket_securityErrorHandler(event:SecurityErrorEvent):void {
    }
    private function socket_socketDataHandler(event:ProgressEvent):void {
      if (socket.bytesAvailable > 0) {
        var value:String = socket.readUTFBytes(socket.bytesAvailable);
      }
    }
    private function socket_ioErrorHandler(event:IOErrorEvent):void {
    }
    private function socket_closeHandler(event:Event):void {
    }
    private function socket_connectedHandler(event:Event):void {
      socket.writeUTFBytes("测试");
      socket.flush();
    }
  }
}
